package com.lifu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lifu.yygh.oss.service.FileService;
import com.lifu.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Description
 * @Author lifu
 * @Date 2021/5/22 12:56
 */
@Service
public class FileServiceImpl implements FileService {

    //上传文件到阿里云oss
    @Override
    public String upload(MultipartFile multipartFile) {
        String endpoint = ConstantOssPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //生成一个唯一的文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        //按照日期创建文件夹
        String timeUrl = new DateTime().toString("yyyy/MM/dd");
        String fileName = timeUrl + "/" + uuid+multipartFile.getOriginalFilename();

        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(bucketName, fileName ,inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        //返回上传后的路径
        String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
        return url;
    }
}
